/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controler;

import Model.Dao.DAOSanPham;
import Model.Pojo.Danhmucsanpham;
import Model.Pojo.Hinhanh;
import Model.Pojo.Sanpham;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xml.sax.SAXException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;

/**
 *
 * @author THANH QUAN
 */
public class ThemSuaSanPham
        extends HttpServlet
{

    private boolean isMultipart;
    private String filePath = "img/";
    private int maxFileSize = 10 * 1024 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param requestHTML servlet requestHTML
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest requestHTML, HttpServletResponse response)
            throws ServletException, IOException
    {
        requestHTML.setAttribute("QUAN_LY_SAN_PHAM", "1");
        response.setContentType("text/html; charset=UTF-8");
        requestHTML.setCharacterEncoding("UTF8");
        DAOSanPham daoSP = new DAOSanPham();
        Sanpham dtoSP = null;

        HttpSession session = requestHTML.getSession(true);
        dtoSP = (Sanpham) session.getAttribute("CHI_TIET_SAN_PHAM");

        //Cap nhat thong tin san pham
        if (dtoSP != null)//Cap nhat san pham
        {
            try
            {
                dtoSP.setId(dtoSP.getId());
                dtoSP.setGiagoc((BigDecimal.valueOf((Double.valueOf(requestHTML.
                        getParameter("txtGiaGoc"))))));
                dtoSP.setGiamgia(Integer.parseInt(requestHTML.
                        getParameter("txtChietKhau")));
                dtoSP.setGiaban((BigDecimal.valueOf(
                        dtoSP.getGiagoc().doubleValue() * (1 - (double) dtoSP.getGiamgia() / 100))));
                dtoSP.setNgaydangsanpham(new Date());
                dtoSP.setNgayketthuc(CXuLy.ConvertStringToDate(requestHTML.
                        getParameter("txtNgayKetThuc")));
                dtoSP.setNoidungdai(requestHTML.getParameter("txtBaiVietSanPham"));
                dtoSP.setNoidungngan(requestHTML.getParameter("txtTieuDeSanPham"));
                dtoSP.setSoluong(Integer.parseInt(requestHTML.getParameter("txtSoLuong")));
                dtoSP.setTensp(requestHTML.getParameter("txtTenSanPham"));
                dtoSP.setTinhtrang(Boolean.TRUE);
                dtoSP.setTinhtrangbanhang(1);

                XuLyXpath(dtoSP, dtoSP.getNoidungdai());

                daoSP.UpdateSanPham(dtoSP);
                session.removeAttribute("CHI_TIET_SAN_PHAM");
                response.sendRedirect("danh-sach-san-pham.htm");
                return;
            }
            catch (Exception ex)
            {
                requestHTML.setAttribute("ERROR", "Cập nhập dữ liệu không thành công.");
            }
        }
        else//Insert san pham moi
        {
            try
            {
                dtoSP = new Sanpham();

                dtoSP.setGiagoc((BigDecimal.valueOf((Double.valueOf(requestHTML.
                        getParameter("txtGiaGoc"))))));
                dtoSP.setGiamgia(Integer.parseInt(requestHTML.
                        getParameter("txtChietKhau")));
                dtoSP.setGiaban((BigDecimal.valueOf(
                        dtoSP.getGiagoc().doubleValue() * (1 - (double) dtoSP.getGiamgia() / 100))));
                dtoSP.setMasp(requestHTML.getParameter("txtMaSanPham"));
                dtoSP.setNgaydangsanpham(new Date());
                dtoSP.setNgayketthuc(CXuLy.ConvertStringToDate(requestHTML.
                        getParameter("txtNgayKetThuc")));
                dtoSP.setNoidungdai(requestHTML.getParameter("txtBaiVietSanPham"));
                dtoSP.setNoidungngan(requestHTML.getParameter("txtTieuDeSanPham"));
                dtoSP.setSoluong(Integer.parseInt(requestHTML.getParameter("txtSoLuong")));
                dtoSP.setTensp(requestHTML.getParameter("txtTenSanPham"));
                dtoSP.setTinhtrang(Boolean.TRUE);
                dtoSP.setTinhtrangbanhang(1);

                XuLyXpath(dtoSP, dtoSP.getNoidungdai());
                //UpLoadAnh(requestHTML, response);

                Danhmucsanpham dtoDMSP = new Danhmucsanpham();
                dtoDMSP.setId(Integer.valueOf(requestHTML.getParameter("cboDanhMucSanPham")));
                dtoSP.setDanhmucsanpham(dtoDMSP);

                daoSP.InsertSanPham(dtoSP);
            }
            catch (Exception ex)
            {
                requestHTML.setAttribute("ERROR", "Thêm sản phẩm không thành công.\n" + ex.
                        getMessage());
            }
            //nhay sang trang moi
            RequestDispatcher view = requestHTML.getRequestDispatcher("them-san-pham.jsp");
            view.forward(requestHTML, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        if(!CXuLy.PhanQuyen(request, response))
        {
            return;
        }

        request.setAttribute("QUAN_LY_SAN_PHAM", "1");

        String strid_sanpham = request.getParameter("query");
        String url = request.getServletPath();
        //Cap nhat thong tin khach hang
        if (url.equals("/cap-nhat-san-pham.htm"))
        {
            request.setAttribute("CAP_NHAT_SAN_PHAM", "1");
            if (strid_sanpham == null)
            {
                request.setAttribute("ERROR", "The page you request was not found.");
            }
            else
            {
                try
                {
                    int id_sanpham = Integer.parseInt(strid_sanpham);

                    //lay thong tin khach hang
                    Sanpham dtoSP = null;
                    DAOSanPham daoSP = new DAOSanPham();

                    dtoSP = daoSP.ChiTieSanPham(id_sanpham);

                    if (dtoSP == null)
                    {
                        request.setAttribute("ERROR", "The page you request was not found.");
                    }
                    else
                    {
                        request.setAttribute("CHI_TIET_SAN_PHAM", dtoSP);
                        HttpSession session = request.getSession(true);
                        session.setAttribute("CHI_TIET_SAN_PHAM", dtoSP);
                    }
                }
                catch (Exception ex)
                {
                    request.setAttribute("ERROR", "The page you request was not found.");
                }
            }
        }


        RequestDispatcher view = request.getRequestDispatcher("them-san-pham.jsp");
        view.forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
//
//    private void UpLoadAnh(HttpServletRequest requestHTML, HttpServletResponse response) throws
//            IOException
//    {
//        String[] str = requestHTML.getParameterValues("fileupload");
//        isMultipart = ServletFileUpload.isMultipartContent(requestHTML);
//        response.setContentType("text/html");
//        java.io.PrintWriter out = response.getWriter();
//        if (!isMultipart)
//        {
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet upload</title>");
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<p>No file uploaded</p>");
//            out.println("</body>");
//            out.println("</html>");
//            // return;
//        }
//        DiskFileItemFactory factory = new DiskFileItemFactory();
//        // maximum size that will be stored in memory
//        factory.setSizeThreshold(maxMemSize);
//        // Location to save data that is larger than maxMemSize.
//        factory.setRepository(new File("c:\\img"));
//
//        // Create a new file upload handler
//        ServletFileUpload upload = new ServletFileUpload(factory);
//        // maximum file size to be uploaded.
//        upload.setSizeMax(maxFileSize);
//
//        try
//        {
//            // Parse the request to get file items.
//            List fileItems = upload.parseRequest(requestHTML);
//
//            // Process the uploaded file items
//            Iterator i = fileItems.iterator();
//
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet upload</title>");
//            out.println("</head>");
//            out.println("<body>");
//            while (i.hasNext())
//            {
//                FileItem fi = (FileItem) i.next();
//                if (!fi.isFormField())
//                {
//                    // Get the uploaded file parameters
//                    String fieldName = fi.getFieldName();
//                    String fileName = fi.getName();
//                    String contentType = fi.getContentType();
//                    boolean isInMemory = fi.isInMemory();
//                    long sizeInBytes = fi.getSize();
//                    // Write the file
//                    if (fileName.lastIndexOf("\\") >= 0)
//                    {
//                        file = new File(filePath
//                                + fileName.substring(fileName.lastIndexOf("\\")));
//                    }
//                    else
//                    {
//                        file = new File(filePath
//                                + fileName.substring(fileName.lastIndexOf("\\") + 1));
//                    }
//                    fi.write(file);
//                    out.println("Uploaded Filename: " + fileName + "<br>");
//                }
//            }
//            out.println("</body>");
//            out.println("</html>");
//        }
//        catch (Exception ex)
//        {
//            System.out.println(ex);
//        }
//
//    }

    private void XuLyXpath(Sanpham dtoSP, String noidungdai)
    {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try
        {
            builder = builderFactory.newDocumentBuilder();

            String str = "<root>" + noidungdai.replace("alt=\"\">", "/>").replace("<br>", "").
                    replace("\t", "").replace("\r", "").replace("\n", "") + "</root>";

            Document document = builder.parse(new ByteArrayInputStream(str.getBytes()));
            XPath xPath = XPathFactory.newInstance().newXPath();
            String expression = "//@src";
            NodeList nodeList1 = (NodeList) xPath.compile(expression).evaluate(document,
                                                                               XPathConstants.NODESET);
            dtoSP.getHinhanhs().clear();
            if (nodeList1.getLength() != 0)
            {
                dtoSP.setAnhdaidein(nodeList1.item(0).getNodeValue());
                Set<Hinhanh> list = new HashSet<Hinhanh>();

                for (int i = 0; i < nodeList1.getLength(); i++)
                {
                    Hinhanh dtoHinhAnh = new Hinhanh();
                    dtoHinhAnh.setDuongdan(nodeList1.item(i).getNodeValue());
                    dtoHinhAnh.setSanpham(dtoSP);
                    list.add(dtoHinhAnh);
                }
                dtoSP.setHinhanhs(list);
            }

        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (SAXException ex)
        {
            Logger.getLogger(ThemSuaSanPham.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex)
        {
            Logger.getLogger(ThemSuaSanPham.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (XPathExpressionException ex)
        {
            Logger.getLogger(ThemSuaSanPham.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
